<template>
  <div>
    <el-form :inline="true" :model="searchForm" class="demo-form-inline">
      <el-form-item>
        <el-input v-model="searchForm.name" placeholder="名称" clearable/>
      </el-form-item>
      <el-form-item>
        <el-button @click="getRoleList">搜索</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="dialogVisible = true">新增</el-button>
      </el-form-item>
      <el-form-item>
        <el-popconfirm title="这是一段内容确定删除吗？" @confirm="delHandle(null)">
          <el-button slot="reference" type="danger" :disabled="disabledStatu">批量删除</el-button>
        </el-popconfirm>
      </el-form-item>
    </el-form>

    <el-table border stripe ref="multipleTable" :data="tableData" tooltip-effect="dark" style="width: 100%"
              @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column prop="name" label="名称" width="120"></el-table-column>
      <el-table-column prop="code" label="唯一编码"></el-table-column>
      <el-table-column prop="remark" label="描述"></el-table-column>
      <el-table-column prop="statu" label="状态" sortable width="150">
        <template slot-scope="scope">
          <el-tag size="small" v-if="scope.row.statu===1" type="success">正常</el-tag>
          <el-tag size="small" v-else type="danger">禁用</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="path" label="操作" sortable width="200">
        <template slot-scope="scope">
          <el-button type="text" @click="permHandle(scope.row.id)">分配权限</el-button>
          <el-button type="text" @click="editHandle(scope.row.id)">编辑</el-button>
          <el-divider direction="vertical"></el-divider>
          <template>
            <el-popconfirm
                title="这是一段内容确定删除吗？"
                @confirm="delHandle(scope.row.id)"
            >
              <el-button slot="reference" type="text">删除</el-button>
            </el-popconfirm>
          </template>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        layout="total, sizes, prev, pager, next, jumper"
        :page-sizes="[10, 20, 50, 100]"
        :current-page="current"
        :page-size="size"
        :total="total">
    </el-pagination>


    <!--对话框-->
    <el-dialog
        title="提示"
        :visible.sync="dialogVisible"
        width="600px"
        :before-close="handleClose">
      <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="100px" class="demo-editForm">

        <el-form-item label="角色名称" prop="name">
          <el-input v-model="editForm.name"></el-input>
        </el-form-item>
        <el-form-item label="唯一编码" prop="code">
          <el-input v-model="editForm.code"></el-input>
        </el-form-item>
        <el-form-item label="描述" prop="remark" label-width="100px">
          <el-input v-model="editForm.remark" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="状态" prop="statu" label-width="100px">
          <el-radio-group v-model="editForm.statu">
            <el-radio :label=0>禁用</el-radio>
            <el-radio :label=1>正常</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="submitForm('editFormRef')">立即创建</el-button>
          <el-button @click="resetFields('editFormRef')">重置</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <el-dialog
        title="分配权限"
        :visible.sync="permDialogVisible"
        width="600px"
    >
      <el-form :model="permForm" label-width="100px" class="demo-editForm">
        <el-tree
            ref="permTree"
            :check-strictly="true"
            :data="perTreeData"
            show-checkbox
            node-key="id"
            :default-expand-all="true"
            :props="defaultProps">
        </el-tree>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="permDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitPermFormHandle('permForm')">确 定</el-button>
     </span>
    </el-dialog>
  </div>
</template>

<script>
import axios from "@/axios";
import qs from 'qs'

export default {
  name: "Role",
  data() {
    return {
      size: 10,
      total: 0,
      current: 1,
      searchForm: {},
      editForm: {},
      permForm: {},
      perTreeData: [],
      permDialogVisible: false,
      dialogVisible: false,
      disabledStatu: true,
      tableData: [
        {
          name: '普通用户',
          code: 'normal',
          statu: 1,
          remark: '普通用户'
        }, {
          name: '超级管理员',
          code: 'admin',
          statu: 1,
          remark: '超级管理员'
        },
      ],
      editFormRules: {
        name: [{required: true, message: '请输入角色名称', trigger: 'blur'}],
        code: [{required: true, message: '请输入唯一编码', trigger: 'blur'}],
        remark: [{required: true, message: '请输入描述', trigger: 'blur'}],
        type: [{required: true, message: '请选择状态', trigger: 'blur'}],
        statu: [{required: true, message: '请选择状态', trigger: 'blur'}]
      },
      multipleSelection: [],
      defaultProps: {
        children: 'children',
        label: 'name',
      }
    }
  },
  created() {
    this.getRoleList()
    axios({
      url: '/sys/menu/list',
      method: 'GET'
    }).then(res => {
      this.perTreeData = res.data.data
    })
  },
  methods: {
    submitPermFormHandle() {
      let menuIds = this.$refs.permTree.getCheckedKeys()
      let params = {}
      let id = this.permForm.id
      Object.assign(params, {menuIds}, {id})
      console.log("---》", params)
      axios({
        url: `/sys/role/perm/${id}`,
        method: 'POST',
        data: menuIds

      }).then(() => {
        this.$message.success("操作成功!")
        this.permDialogVisible = false
      })
    },
    permHandle(id) {
      this.permDialogVisible = true
      axios({
        url: '/sys/role/info/',
        method: 'GET',
        params: {
          id
        }
      }).then(res => {
        this.$refs.permTree.setCheckedKeys(res.data.data.menuIds)
        this.permForm = res.data.data
      })
    },
    getRoleList() {
      axios(
          {
            url: '/sys/role/list',
            method: 'GET',
            params: {
              name: this.searchForm.name,
              size: this.size,
              current: this.current
            }
          }
      ).then(res => {
        console.log(res.data.data)

        this.tableData = res.data.data.records
        this.size = res.data.data.size
        this.current = res.data.data.current
        this.total = res.data.data.total
      })
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.$axios.post('sys/role/' + (this.editForm.id ? 'update' : 'save'), this.editForm)
              .then(res => {
                this.getRoleList()
                this.$message.success("操作成功!")
                this.dialogVisible = false
                this.resetFields(formName)
              })
        } else {
          this.$message.error("操作失败!")
          this.dialogVisible = false
        }
      })
    },
    delHandle(id) {

      let ids = []
      if (id) {
        ids.push(id)
      } else {
        this.multipleSelection.forEach(row => {
          ids.push(row.id)
        })
      }
      /*params.ids = ids
      //Object.assign(params,ids)
      console.log("params->",params)*/
      axios({
        url: '/sys/role/delete',
        method: 'POST',
        data: ids
      }).then(() => {
        this.$message.success("删除成功!")
        this.getRoleList()
      })
      /*this.$axios.post("/sys/role/delete", ids).then(res => {
        this.$message({
          showClose: true,
          message: '恭喜你，操作成功',
          type: 'success',
          onClose:() => {
            this.getRoleList()
          }
        });
      })*/
    },
    editHandle(id) {
      axios({
        url: '/sys/role/info/',
        method: 'GET',
        params: {id}
      }).then(res => {
        console.log(res.data.data)
        this.editForm = res.data.data
        this.dialogVisible = true
      })
    },
    handleClose() {
      this.resetFields('editFormRef')
    },
    resetFields(formName) {
      this.dialogVisible = false
      //清空表单
      this.$refs[formName].resetFields()
      this.editForm = {}
      //重置校验
      this.$refs[formName].clearValidate()
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.size = val
      this.getRoleList()
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.current = val
      this.getRoleList()
    },
    toggleSelection(rows) {
      if (rows) {
        rows.forEach(row => {
          this.$refs.multipleTable.toggleRowSelection(row);
        });
      } else {
        this.$refs.multipleTable.clearSelection();
      }
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;

      this.disabledStatu = val.length === 0
    }
  }
}
</script>

<style scoped>
.el-pagination {
  /**
    分页条向右偏移
    分页条距离上端15px
  **/
  float: right;
  margin-top: 15px;
}
</style>
